package com.hakgc.rent.web.servlet;

import com.hakgc.rent.entity.District;
import com.hakgc.rent.service.DistrictService;
import com.hakgc.rent.service.impl.DistrictServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Xing.Jiejian
 * @date 2020/11/10
 */
@WebServlet(name = "UpdateDistrictServlet",urlPatterns = "/rent/district/update")
public class UpdateDistrictServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String strId = request.getParameter("id");
        int id = -1;
        if (strId!=null){
            id = Integer.parseInt(strId);
        }
        String name = request.getParameter("name");
        District district = new District(id,name);

        DistrictService districtService = new DistrictServiceImpl();
        if (districtService.update(district)){
            // 修改成功，提示信息，跳转列表页
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("<script>");
            out.println("alert('修改成功！');");
            out.println("location.href='"+request.getContextPath()+"/rent/districts';");
            out.println("</script>");

        }else{
            // 修改失败，将失败信息转发会表单页
            request.setAttribute("errorMsg","区县保存失败，请重新操作！");
            request.setAttribute("dis",district);
            request.getRequestDispatcher("/rent/districtUpdate.jsp").forward(request,response);
        }

    }

    /**
     * 跳转修改页，初始化区县信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String strId = request.getParameter("id");
        if (strId!=null){
            int id = Integer.parseInt(strId);
            DistrictService districtService = new DistrictServiceImpl();
            District district = districtService.findById(id);
            // 保存作用域request，转发到页面
            request.setAttribute("dis",district);
            request.getRequestDispatcher("/rent/districtUpdate.jsp").forward(request,response);
        }
        // TODO 如果没有传入id字段则不允许进入修改页，可以提示错误信息，然后跳转列表页或者错误提示页

    }
}
